/*
 * Copyright (c) 2014, 2015, XIANDIAN and/or its affiliates. All rights reserved.
 * XIANDIAN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 */
package com.xiandian.cloud.storage.signup;

import java.util.List;
import com.woorea.openstack.keystone.model.Tenant;
import com.woorea.openstack.swift.Swift;
import com.woorea.openstack.swift.model.Container;
import com.woorea.openstack.swift.model.Object;
import com.xiandian.cloud.storage.ObjectListActivity;
import com.xiandian.cloud.storage.R;
import com.xiandian.cloud.storage.base.OpenstackApplicationState;
import com.xiandian.cloud.storage.base.TaskResult;
import com.xiandian.cloud.storage.sdk.service.OpenStackClientService;
import com.xiandian.cloud.storage.utils.PromptDialogUtil;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

/**
 * 登录Activity
 * @author 云计算应用与开发项目组
 * @since  V1.0
 */
public class LoginActivity extends Activity {
	
	//如果没有Swift情况下（不联网），可以模拟登录主界面。
	//Swift网络可连接时间，该参数设置成false
	private boolean DEMO = true;

	/** The progress bar. */
	protected ProgressBar progressBar;

	/** The txt username. */
	EditText txtUsername;

	/** The txt password. */
	EditText txtPassword;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		progressBar = (ProgressBar) findViewById(R.id.servicesProgressBar);
		progressBar.setIndeterminate(true);
		progressBar.bringToFront();
		progressBar.setVisibility(View.INVISIBLE);
		txtUsername = (EditText) findViewById(R.id.txtUsername);
		txtUsername.setText("gs0001"); // 登录用户名->容器名称->租户名称
		txtPassword = (EditText) findViewById(R.id.txtPassword);
		txtPassword.setText("B8m721NB");
		Button btLogin = (Button) findViewById(R.id.btnLogin);
		btLogin.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				progressBar.setVisibility(View.VISIBLE);
				OpenStackClientService service = getService();
				service.setKeystoneAuthUrl("http://192.168.0.102:5000/v2.0");
				service.setKeystoneAdminAuthUrl("http://192.168.0.102:5000/v2.0");
				service.setKeystoneEndpoint("http://192.168.0.102:5000/v2.0");
				service.setTenantName(txtUsername.getText().toString());
				service.setKeystonePassword(txtPassword.getText().toString());
				service.setKeystoneUsername(txtUsername.getText().toString());
				
				// 获取项目
				GetTenantsTask getTenantsTask=new GetTenantsTask();
				getTenantsTask.execute();
			}
		});
	}
	
	/**
	 * 获取Tenant,成功后获取容器
	 * @author Zero Cool
	 *
	 */
	private class GetTenantsTask extends AsyncTask<String, Object, TaskResult<Tenant>>{

		@Override
		protected TaskResult<Tenant> doInBackground(String... params) {
			// TODO Auto-generated method stub
			try {
				return new TaskResult<Tenant>(
						getService()
						.getKeystone()
						.tenants()
						.list()
						.execute()
						.getList().get(0));
			} catch (Exception e) {
				getService().resetConnection();
				return new TaskResult<Tenant>(e);
			}
		}

		@Override
		protected void onPostExecute(TaskResult<Tenant> result) {
			//模拟登录，正式开发注释掉			
			if ( DEMO) {				
				getApplicationState().setSelectedTenant((Tenant) result.getResult());				
				// 获取Container
				GetContainerTask getContainerTask=new GetContainerTask();
				getContainerTask.execute();				
			}
			
			if (result.isValid()) {				
				getApplicationState().setSelectedTenant((Tenant) result.getResult());				
				// 获取Container
				GetContainerTask getContainerTask=new GetContainerTask();
				getContainerTask.execute();
				
			} else {
				PromptDialogUtil.showErrorDialog(
						LoginActivity.this, 
						R.string.error_dlg,
						result.getException(), 
						null);
			}
		}
	}
	
	
	/**
	 * 获取Container
	 * @author Zero Cool
	 *
	 */
	private class GetContainerTask extends AsyncTask<String, Object, TaskResult<Container>>{

		@Override
		protected TaskResult<Container> doInBackground(String... params) {
			try {
				Swift swift = getService().getSwift(
						getApplicationState()
						.getSelectedTenant()
						.getId());
				List<Container> tempList = 
						swift.containers().list().execute().getList();
				Container container = null;
				for(int i=0;i<tempList.size();i++){
					if(tempList.get(i).getName().equals(getService().getTenantName())){
						container=tempList.get(i);
						return new TaskResult<Container>(container);
					}
				}
				return new TaskResult<Container>(container);
			}catch (Exception e) {
				return new TaskResult<Container>(e);
			}
		}

		@Override
		protected void onPostExecute(TaskResult<Container> result) {
			
			//模拟登录，正式开发注释掉			
			if ( DEMO) {				
				getApplicationState().setSelectedContainer((Container)result.getResult());

				Intent intent = new Intent(LoginActivity.this,
						ObjectListActivity.class);
				startActivity(intent);
				finish();		
			}
			
			if (result.isValid()) {
				if(result.getResult()==null){
					// 创建容器
					CreateContainerTask createContainerTask=new CreateContainerTask(getService().getTenantName());
					createContainerTask.execute();
				}
				else{
					getApplicationState().setSelectedContainer((Container)result.getResult());

					Intent intent = new Intent(LoginActivity.this,
							ObjectListActivity.class);
					startActivity(intent);
					finish();
				}
				
			} else {
				PromptDialogUtil.showErrorDialog(
						LoginActivity.this, 
						R.string.error_dlg,
						result.getException(), 
						null);
			}
		}
	}
	
	private OpenstackApplicationState getApplicationState(){
		return OpenstackApplicationState.getInstance();
	}

	private OpenStackClientService getService(){
		return OpenStackClientService.getInstance();
	}
	
	private class CreateContainerTask extends
	AsyncTask<String, Object, TaskResult<Container>> {

		/** The container name. */
		private String containerName;

		/**
		 * Instantiates a new creates the container task.
		 * 
		 * @param containerName
		 *            the container name
		 */
		private CreateContainerTask(String containerName) {
			this.containerName = containerName;
		}

		protected TaskResult<Container> doInBackground(String... params) {
			try {
				Swift swift = getService().getSwift(
						getApplicationState().getSelectedTenant().getId());
				swift.containers().create(containerName).execute();
				swift.containers().create("garbage_"+containerName).execute();				
				Container container = new Container();
				container.setName(containerName);
				return new TaskResult<Container>(container);
			} catch (Exception e) {
				return new TaskResult<Container>(e);
			}
		}
		
		protected void onPostExecute(TaskResult<Container> result) {
			progressBar.setVisibility(View.GONE);
			if (result.isValid()) {
				getApplicationState().setSelectedContainer((Container)result.getResult());

				Intent intent = new Intent(LoginActivity.this,
						ObjectListActivity.class);
				startActivity(intent);
				finish();
			} else {
				PromptDialogUtil.showErrorDialog(
						LoginActivity.this, 
						R.string.error_dlg, 
						result.getException(), 
						null);
			}
		}
	}
	
}